package com.llkj.qingnianguoxue.circle;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.adapter.CircleMemberAdapter;
import com.llkj.qingnianguoxue.base.BaseActivity;
import com.llkj.qingnianguoxue.base.ConstantUserInfo;
import com.llkj.qingnianguoxue.base.MyApplication;
import com.llkj.qingnianguoxue.bean.CircleListBean;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.util.DisplayUtil;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.RxBus;
import com.llkj.qingnianguoxue.util.StringUtils;
import com.llkj.qingnianguoxue.util.ToastUtil;
import com.llkj.qingnianguoxue.util.helper.LoadDataHelper;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.llkj.qingnianguoxue.circle.CircleOwnerDetailActivity.IS_REPORT;

/**
 * 全部成员
 */
public class CircleMemberActivity extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener,
        LoadDataHelper.LoadMoreListener, SwipeRefreshLayout.OnRefreshListener{
    public static final int REQUEST_CODE_ADD_FRIEND = 8901;
    @BindView(R.id.ll_search)
    LinearLayout llSearch;
    @BindView(R.id.et_search)
    protected EditText etSearch;
    @BindView(R.id.refresh_layout)
    protected SwipeRefreshLayout refreshLayout;
    @BindView(R.id.recyclerView)
    protected RecyclerView lvMembers;//成员
    private CircleMemberAdapter memberAdapter;
    private List<CircleListBean.CircleBean> mMemberData;//成员数据
    private int mCurrentPosition;
    private int dialogType=0;//弹框类型
    private int totalSize, mPage;
    private String mSearchKey,mGroupId;//搜索，群id
    private int mReceiveRefuse;//2接受，3拒绝

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_circle_all_member);
        setTitle("全部成员", true, TITLE_TYPE_IMG, R.drawable.icon_back, false, -1, -1);
        initStatusbar(TSATUSBAR_TYPE_BLACK_TEXT,rlTitle,R.color.gray_bar);
        ButterKnife.bind(this);
        Intent intent =  getIntent();
        mGroupId = intent.getStringExtra("groupId");

        initView();
        initListener();

        loadWaitDialog();
        onRefresh();
    }

    private void initView(){
        llSearch.setVisibility(View.GONE);
//        etSearch = (EditText) findViewById(R.id.et_search);
//        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.refresh_layout);
        refreshLayout.setColorSchemeResources(R.color.blue3989ff);
//        lvMembers = (RecyclerView) findViewById(R.id.recyclerView);
        int padding = DisplayUtil.dip2px(this, 10);
        lvMembers.setPadding(padding, 0, padding, 0);
        lvMembers.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        mMemberData = new ArrayList<>();
        memberAdapter = new CircleMemberAdapter(R.layout.item_circle_all_member,mMemberData);
        lvMembers.setAdapter(memberAdapter);
    }

    private void initListener(){
        refreshLayout.setOnRefreshListener(this);
        memberAdapter.setOnLoadMoreListener(this);
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_NEXT || actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_SEND) {
                    String word = etSearch.getText().toString();
                    if (!StringUtils.isEmpty(word)) {
                        if (StringUtils.isContaintSymbol(word)) {
                            ToastUtil.makeLongText(CircleMemberActivity.this, "对不起，请不要输入特殊字符");
                            return true;
                        }
                        mSearchKey = word;
                        onRefresh();
                    } else {
                        ToastUtil.makeLongText(CircleMemberActivity.this, "请输入搜索关键字");
                    }
                }
                return true;
            }
        });

        lvMembers.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                mCurrentPosition = position;
                CircleListBean.CircleBean item = mMemberData.get(position);
                if(view.getId()== R.id.tv_add_friend){//加好友
                    if(item.getIs_friend()==2){
                        ToastUtil.makeLongText(CircleMemberActivity.this,getString(R.string.friend_request_again));
                        return;
                    }else if(item.getIs_friend()==4){
                        Bundle bundle = new Bundle();
                        bundle.putString("uid",item.getId());
                        startActivityForResult(AppyVerificationActivity.class,bundle,REQUEST_CODE_ADD_FRIEND);
                    }else if(item.getIs_friend()==3){//待确认
                        dialogConfirm(getString(R.string.dialog_addfriend_title), null,  getString(R.string.friend_refuse), getString(R.string.friend_accept)).show();
                    }

                }else if(view.getId()== R.id.iv_chat){//聊天
                    MyChatActivity.startSingleChat(CircleMemberActivity.this,item.getName(),item.getHx_id(),item.getUid());
                }
            }
        });
        lvMembers.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                CircleListBean.CircleBean item = mMemberData.get(position);
                String uid = MyApplication.getInstance().sputil.getString(ConstantUserInfo.USER_ID);
                if(!uid.equals(item.getId())) {
                    //进入个人主页
                    Bundle bundle = new Bundle();
                    bundle.putBoolean(IS_REPORT, true);
                    bundle.putString("ownerId",item.getId());
                    bundle.putString("circleId",mGroupId);
                    startActivity(CircleOwnerDetailActivity.class, bundle);
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK && requestCode == REQUEST_CODE_ADD_FRIEND){
            CircleListBean.CircleBean item = mMemberData.get(mCurrentPosition);
            item.setIs_friend(2);
            memberAdapter.notifyItemChanged(mCurrentPosition);
        }
    }

    @Override
    protected void dialogLeftBtn() {
        super.dialogLeftBtn();
        mReceiveRefuse = 3;
        CircleListBean.CircleBean item = mMemberData.get(mCurrentPosition);
        setAcceptRefuse(item.getId(),"2");
    }

    @Override
    protected void dialogRightBtn() {
        super.dialogRightBtn();
        CircleListBean.CircleBean item = mMemberData.get(mCurrentPosition);
        mReceiveRefuse = 2;
        setAcceptRefuse(item.getId(),"1");
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
        if(method == HttpMethod.HTTP_CIRCLE_MEMBER){//圈子成员
            try {
                CircleListBean circleListBean = GsonUtil.GsonToListBean(data, CircleListBean.class);
                if(circleListBean != null){
                    try {
                        totalSize = Integer.parseInt(circleListBean.getNum());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (mPage == 1) {
                        mMemberData.clear();
                        LoadDataHelper.refreshComplete(memberAdapter, mMemberData, refreshLayout, lvMembers);
                    } else {
                        memberAdapter.setEnableLoadMore(true);
                        memberAdapter.loadMoreComplete();
                    }
                    mMemberData.addAll(circleListBean.getMember());
                    memberAdapter.notifyDataSetChanged();
                    if (totalSize == 0) {
                        ToastUtil.makeShortText(this, "没有找到相应内容");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(method == HttpMethod.HTTP_CIRCLE_SECEDE){//退出圈子
            RxBus.getInstance().post(ConstantUserInfo.REFRESH_CIRCLE);
            Intent intent = new Intent();
            intent.putExtra("secede","");
            setResult(RESULT_OK, intent);
            finish();
        }/*else if(method == HttpMethod.HTTP_CIRCLE_ADD_FRIEND) {//6.6发起好友申请
            dialogType = 0;
            dialogPrompt("发送成功", "等待对方认证", "确定").show();
            try {
                CircleListBean.CircleBean item = mMemberData.get(mCurrentPosition);
                item.setIs_friend(2);
                memberAdapter.notifyItemChanged(mCurrentPosition);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }*/else if(method == HttpMethod.HTTP_USER_ADD_FRIEND) {//8.4接受和不接受好友申请
            try {
//                CircleListBean.CircleBean item = mMemberData.get(mCurrentPosition);
//                item.setIs_friend(1);
////                item.setState(String.valueOf(mReceiveRefuse));
//                memberAdapter.notifyItemChanged(mCurrentPosition);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取成员
     */
    private void getMemberData(){
        HttpMethod.circleMember(this,this,mSearchKey,mGroupId, String.valueOf(mPage));
    }
    /**
     * 接受拒绝
     * @param formId
     * 好友id
     * @param type
     * 1接受 2 不接受
     */
    private void setAcceptRefuse(String formId, String type){
        loadWaitDialog();
        HttpMethod.userAddFriend(this, this, formId, type);
    }

    @Override
    protected void onhttpFailed(String message, int method) {
        super.onhttpFailed(message, method);
        if(!StringUtils.isEmpty(message)){
            ToastUtil.makeLongText(this,message);
        }
    }

    @Override
    public void onLoadMore() {
        mPage++;
        getMemberData();
    }

    @Override
    public void onRefresh() {
        mPage = 1;
        getMemberData();
    }

    @Override
    public void onLoadMoreRequested() {
        LoadDataHelper.loadMoreRequest(this, memberAdapter, null, lvMembers, totalSize);
    }

}
